package cn.lili.modules.payment.kit.plugin.wallet;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.DictCodeEnum;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.utils.SysDictUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.dict.entity.vos.SysDictItemVO;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.member.entity.dos.*;
import cn.lili.modules.member.entity.vo.GradeVO;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.*;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.member.service.RechargeFowService;
import cn.lili.modules.member.service.RechargeFowService;
import cn.lili.modules.order.aftersale.service.AfterSaleService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.enums.DeliverStatusEnum;
import cn.lili.modules.order.order.entity.vo.OrderVO;
import cn.lili.modules.order.order.service.OrderItemService;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.payment.entity.RefundLog;
import cn.lili.modules.payment.entity.enums.CashierEnum;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.payment.kit.CashierSupport;
import cn.lili.modules.payment.kit.Payment;
import cn.lili.modules.payment.kit.dto.PayParam;
import cn.lili.modules.payment.kit.dto.PaymentSuccessParams;
import cn.lili.modules.payment.kit.params.dto.CashierParam;
import cn.lili.modules.payment.service.PaymentService;
import cn.lili.modules.payment.service.RefundLogService;
import cn.lili.modules.permission.entity.dos.Role;
import cn.lili.modules.permission.mapper.RoleMapper;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.vos.StoreDetailVO;
import cn.lili.modules.store.mapper.StoreDetailMapper;
import cn.lili.modules.store.mapper.StoreMapper;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.mapper.RegionMapper;
import cn.lili.modules.system.service.SettingService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawApply;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawItem;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.RechargeService;
import cn.lili.modules.wallet.service.WalletLogDetailService;
import cn.lili.modules.wallet.entity.vo.MemberSalesWithdrawVO;
import cn.lili.modules.wallet.service.*;
import cn.lili.modules.wallet.serviceimpl.MemberWalletServiceImpl;
import cn.lili.modules.whitebar.entity.dos.RateSetting;
import cn.lili.modules.whitebar.mapper.CommissionMapper;
import cn.lili.modules.whitebar.mapper.RateSettingMapper;
import cn.lili.modules.whitebar.service.RateSettingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * WalletPlugin
 *
 * @author Chopper
 * @version v1.0 2021-02-20 10:14
 */
@Slf4j
@Component
public class WalletPlugin implements Payment {

	/**
	 * 支付日志
	 */
	@Autowired
	private PaymentService paymentService;
	/**
	 * 退款日志
	 */
	@Autowired
	private RefundLogService refundLogService;
	/**
	 * 会员余额
	 */
	@Autowired
	private MemberWalletService memberWalletService;
	/**
	 * 收银台
	 */
	@Autowired
	private CashierSupport cashierSupport;

	// 费率
	@Autowired
	private RateSettingMapper rateSettingMapper;

	@Autowired
	private EextensionService eextensionService;

	@Autowired
	private CommissionMapper commissionMapper;

	@Autowired
	private PartnerMapper partnerMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private MemberService memberService;

	@Autowired
	private MemberMapper memberMapper;

	@Autowired
	private GradeLevelMapper gradeLevelMapper;

	@Autowired
	private GradeMapper gradeMapper;
	@Autowired
	private StoreDetailMapper storeDetailMapper;
	@Autowired
	private StoreMapper storeMapper;
	@Autowired
	private OrderService orderService;
	@Autowired
	private RateSettingService rateSettingService;

	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private PartnerService partnerService;

	@Autowired
	private WalletLogDetailService walletLogDetailService;

	@Autowired
	private AfterSaleService afterSaleService;
	// 系统配置
	@Autowired
	private SettingService settingService;

	@Autowired
	private ExtensionMapper extensionMapper;

	@Autowired
	private RegionMapper regionMapper;

	@Autowired
	private TransferService transferService;

	@Autowired
	private MemberWithdrawApplyService memberWithdrawApplyService;

	@Autowired
	private StoreDetailService storeDetailService;

	@Autowired
	private MemberWithdrawItemService memberWalletItemService;

	@Autowired
	private MemberWalletServiceImpl walletDetailService;

	@Autowired
	private RechargeFowService rechargeFowService;

	@Autowired
	private GoodsSkuService getGoodsSkuService;

	/**
	 * 订单货物
	 */
	@Autowired
	private OrderItemService orderItemService;

	@Override
	public ResultMessage<Object> h5pay(HttpServletRequest request, HttpServletResponse response, PayParam payParam) {

		savePaymentLog(payParam);
		return ResultUtil.success(ResultCode.PAY_SUCCESS);
	}

	@Override
	public ResultMessage<Object> jsApiPay(HttpServletRequest request, PayParam payParam) {
		savePaymentLog(payParam);
		return ResultUtil.success(ResultCode.PAY_SUCCESS);
	}

	@Override
	public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) {
		savePaymentLog(payParam);
		return ResultUtil.success(ResultCode.PAY_SUCCESS);
	}

	@Override
	public ResultMessage<Object> nativePay(HttpServletRequest request, PayParam payParam) {
		// if (payParam.getOrderType().equals(CashierEnum.RECHARGE.name())) {
		// throw new ServiceException(ResultCode.CAN_NOT_RECHARGE_WALLET);
		// }
		savePaymentLogNative(payParam);
		return ResultUtil.success(ResultCode.PAY_SUCCESS);
	}

	@Override
	public ResultMessage<Object> transferPay(HttpServletRequest request, PayParam payParam) {
		// if (payParam.getOrderType().equals(CashierEnum.RECHARGE.name())) {
		// throw new ServiceException(ResultCode.CAN_NOT_RECHARGE_WALLET);
		// }
		savePaymentLogTransfer(payParam);
		return ResultUtil.success(ResultCode.PAY_SUCCESS);
	}

	@Override
	public ResultMessage<Object> mpPay(HttpServletRequest request, PayParam payParam) {

		savePaymentLog(payParam);
		return ResultUtil.success(ResultCode.PAY_SUCCESS);
	}

	@Override
	@Transactional
	public void cancel(RefundLog refundLog) {

		memberWalletService.cancelOrder(refundLog.getOrderSn(), true, refundLog.getAfterSaleNo());// 取消订单 退回全部款项
		refundLog.setIsRefund(true);
		refundLogService.save(refundLog);
	}

	/**
	 * 保存支付日志
	 *
	 * @param payParam
	 *            支付参数
	 */
	private void savePaymentLog(PayParam payParam) {
		// 获取支付收银参数
		CashierParam cashierParam = cashierSupport.cashierParam(payParam);
		this.callBack(payParam, cashierParam);
	}

	private void savePaymentLogNative(PayParam payParam) {
		// 获取支付收银参数
		CashierParam cashierParam = cashierSupport.cashierParamNative(payParam);
		this.callBackNative(payParam, cashierParam);
	}

	private void savePaymentLogTransfer(PayParam payParam) {
		// 获取支付收银参数
		CashierParam cashierParam = cashierSupport.cashierParamTransfer(payParam);
		this.callBackTransfer(payParam, cashierParam);
	}

	@Override
	public void refund(RefundLog refundLog) {
		try {
			Order order = orderService.getBySn(refundLog.getOrderSn());
			memberWalletService.cancelOrder(order.getSn(), false, refundLog.getAfterSaleNo());// 取消订单 不退运费
			refundLog.setIsRefund(true);
			refundLogService.save(refundLog);
		} catch (Exception e) {
			log.error("退款失败", e);
		}
	}

	// 计算佣金
	// void countRate(CashierParam cashierParam,MemberVO memberVO,Double rate,String
	// orderType,String owner){
	// List<String> list = Arrays.asList(cashierParam.getOrderSns().split(","));
	// if(CollectionUtils.isNotEmpty(list)){
	// for(String sn : list){
	// String type = "订单[";
	// Double price = 0D;
	// //计算佣金
	// Double flow = 0D;
	// Boolean increase = false;
	// Member member = memberService.getById(UserContext.getCurrentUser().getId());
	// WalletLogDetail walletLogDetail = null;
	// if(orderType.equals(CashierEnum.MEMBER.name())){
	// type = "会员年费订单[";
	// Recharge recharge = rechargeService.getRecharge(sn);
	// price = recharge.getRechargeMoney();
	// owner = WalletOwnerEnum.PROMOTE_HY.name();
	// if("1".equals(member.getHaveStore())){
	// increase = false;
	// }else{
	// String gradeLevel = null;
	// List<GradeVO> gradeVOS = gradeMapper.selectList(new QueryWrapper<>());
	// if(CollectionUtils.isNotEmpty(gradeVOS)){
	// for(GradeVO grade : gradeVOS){
	// if (price.compareTo(grade.getMoney()) == 0 ) {
	// gradeLevel = grade.getLevel();
	// }
	// }
	// }
	// flow = CurrencyUtil.mul(price,rate);
	// walletLogDetail = new WalletLogDetail(
	// null,
	// null,
	// "2",
	// sn,
	// null,
	// null,
	// memberVO.getId(),
	// memberVO.getUsername(),
	// gradeLevel,
	// null,
	// rate.toString(),
	// flow
	// );
	// increase = memberWalletService.increase(new MemberWalletUpdateDTO(flow,
	// memberVO.getId(), type + sn + "]产生佣金[" +
	// flow + "]", DepositServiceTypeEnum.WALLET_COMMISSION.name(), owner),
	// walletLogDetail);
	//
	// }
	// }else if(orderType.equals(CashierEnum.DUES.name())){
	// type = "合伙人年费订单[";
	// Recharge recharge = rechargeService.getRecharge(sn);
	// price = recharge.getRechargeMoney();
	// owner = WalletOwnerEnum.PROMOTE.name();
	// if("1".equals(member.getHaveStore())){
	// increase = false;
	// }else{
	// flow = CurrencyUtil.mul(price,rate);
	// Partner partner = partnerService.getById(member.getStoreId());
	// walletLogDetail = new WalletLogDetail(
	// partner.getRegion(),
	// null,
	// "2",
	// sn,
	// null,
	// null,
	// memberVO.getId(),
	// memberVO.getUsername(),
	// null,
	// null,
	// null,
	// flow
	// );
	// increase = memberWalletService.increase(new MemberWalletUpdateDTO(flow,
	// memberVO.getId(), type + sn + "]产生佣金[" +
	// flow + "]", DepositServiceTypeEnum.WALLET_COMMISSION.name(), owner),
	// walletLogDetail);
	//
	// }
	// }else if(orderType.equals(CashierEnum.SELLER.name())){
	// type = "商家会员年费订单[";
	// Recharge recharge = rechargeService.getRecharge(sn);
	// price = recharge.getRechargeMoney();
	// owner = WalletOwnerEnum.PROMOTE_HY.name();
	// if("1".equals(member.getHaveStore())){
	// flow = CurrencyUtil.mul(price,rate);
	// Store store = storeService.getById(member.getStoreId());
	// walletLogDetail = new WalletLogDetail(
	// store.getStoreAddressPath(),
	// store.getStoreAddressIdPath(),
	// "2",
	// sn,
	// null,
	// null,
	// memberVO.getId(),
	// memberVO.getUsername(),
	// "9999",
	// null,
	// null,
	// flow
	// );
	// increase = memberWalletService.increase(new MemberWalletUpdateDTO(flow,
	// memberVO.getId(), type + sn + "]产生佣金[" +
	// flow + "]", DepositServiceTypeEnum.WALLET_COMMISSION.name(), owner),
	// walletLogDetail);
	//
	// }else{
	// increase = false;
	// }
	// }else{
	// //消费
	// OrderVO bySn = orderService.getBySn(sn);
	// owner = WalletOwnerEnum.PROMOTE.name();
	// if("1".equals(member.getHaveStore())){
	// price = bySn.getGoodsPrice();
	// flow = CurrencyUtil.mul(price,rate);
	// increase = false;
	// }else{
	// price = bySn.getFlowPrice();
	// flow = CurrencyUtil.mul(price,rate);
	// Store store = storeService.getById(bySn.getStoreId());
	// walletLogDetail = new WalletLogDetail(
	// store.getStoreAddressPath(),
	// store.getStoreAddressIdPath(),
	// "2",
	// sn,
	// null,
	// null,
	// memberVO.getId(),
	// memberVO.getUsername(),
	// null,
	// null,
	// null,
	// flow
	// );
	// increase = memberWalletService.increase(new MemberWalletUpdateDTO(flow,
	// memberVO.getId(), type + sn + "]产生佣金[" +
	// flow + "]", DepositServiceTypeEnum.WALLET_COMMISSION.name(), owner),
	// walletLogDetail);
	//
	// }
	//
	// }
	//
	// if(increase) {
	// Commission commission = new Commission();
	// commission.setUserId(memberVO.getId());
	// commission.setUserName(memberVO.getUsername());
	// if (orderType.equals(CashierEnum.MEMBER.name())) {
	// commission.setMember(flow);
	// } else if (orderType.equals(CashierEnum.DUES.name())) {
	// commission.setMember(flow);
	// } else if (orderType.equals(CashierEnum.SELLER.name())) {
	// commission.setMember(flow);
	// } else {
	// commission.setTransactionFlow(flow);
	// }
	// commission.setTransactionTime(cashierParam.getCreateTime());
	// commission.setSerialNumber(cashierParam.getOrderSns());
	// commissionMapper.insert(commission);
	// }
	// };
	// }
	// }

	// 修改合伙人信息
	void updatePartner(String orderType, Double price) {

		MemberVO member = memberService.getUserInfos("BUYER", null);
		// 充值前先把原有的合伙人信息禁用
		partnerMapper.updateByMemberId(UserContext.getCurrentUser().getId());
		Partner partner = new Partner();
		// if(member.getPartnerType() != null){
		// QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
		// queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
		// queryWrapper.eq("partner_type",member.getPartnerType());
		// queryWrapper.eq("partner_state",0);
		// queryWrapper.orderByDesc("end_time");
		// queryWrapper.last("limit 1");
		// partner = partnerMapper.selectOne(queryWrapper);
		// //充值前先把原有的合伙人信息禁用
		// partnerMapper.updateByMemberId(UserContext.getCurrentUser().getId());
		// partner.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
		// partner.setPartnerState(0);
		// partner.setCreateBy(UserContext.getCurrentUser().getId());
		// partner.setCreateTime(new Date());
		// partner.setUpdateBy(null);
		// partner.setUpdateTime(null);
		// }else {
		// 获取时间加一年或加一月或加一天
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);// 设置起时间
		cal.add(Calendar.YEAR, 1);// 增加一年
		partner.setBeginTime(date);
		partner.setEndTime(cal.getTime());
		partner.setMemberId(UserContext.getCurrentUser().getId());
		partner.setPartnerState(0);
		// }
		partner.setPartnerType(0);
		List<SysDictItemVO> allValue = SysDictUtils.getAllValue(DictCodeEnum.PARTNER_PRICE.dictCode());
		if (CollectionUtils.isNotEmpty(allValue)) {
			for (SysDictItemVO sysDictItemVO : allValue) {
				if ("推广员".equals(sysDictItemVO.getItemText())) {
					if (price.compareTo(Double.parseDouble(sysDictItemVO.getItemValue())) == 0) {
						partner.setPartnerType(3);
						QueryWrapper queryWrapper = new QueryWrapper();
						queryWrapper.eq("name", "推广员");
						queryWrapper.eq("parent_id", 0);
						Role role = roleMapper.selectOne(queryWrapper);
						partner.setRoleId(role != null ? role.getId() : null);
						break;
					}
				} else if ("天使合伙人".equals(sysDictItemVO.getItemText())) {
					QueryWrapper queryWrapper = new QueryWrapper();
					queryWrapper.eq("name", "天使合伙人");
					queryWrapper.eq("parent_id", 0);
					Role role = roleMapper.selectOne(queryWrapper);
					if (price.compareTo(Double.parseDouble(sysDictItemVO.getItemValue())) == 0) {
						partner.setPartnerType(2);
						partner.setRoleId(role != null ? role.getId() : null);
						// 商家自动成为天使合伙人
						if (orderType.equals(CashierEnum.SELLER.name())) {
							partner.setPartnerType(2);
							partner.setRoleId(role != null ? role.getId() : null);
						}
						break;
					}
				} else if ("事业合伙人".equals(sysDictItemVO.getItemText())) {
					if (price.compareTo(Double.parseDouble(sysDictItemVO.getItemValue())) == 0) {
						partner.setPartnerType(1);
						QueryWrapper queryWrapper = new QueryWrapper();
						queryWrapper.eq("name", "事业合伙人");
						queryWrapper.eq("parent_id", 0);
						Role role = roleMapper.selectOne(queryWrapper);
						partner.setRoleId(role != null ? role.getId() : null);
						break;
					}
				}
			}
		}
		partnerMapper.insert(partner);
		// 删除原有绑定关系
		extensionMapper.updateByMemberId(UserContext.getCurrentUser().getId());
		// 添加推广码
		Member member1 = new Member();
		member1.setId(member.getId());
		if (StringUtils.isEmpty(member.getPromotionCode())) {
			member1.setPromotionCode(eextensionService.getExtension());
		}
		memberMapper.updateById(member1);

	}

	// 修改会员信息
	void updateMember(Double price, String owner) {

		// MemberVO member = memberService.getUserInfos("BUYER",null);
		// 充值前先把原有的会员信息禁用
		gradeLevelMapper.updateByMemberId(UserContext.getCurrentUser().getId(), owner);
		// if(member != null && member.getGradeId() != null){
		// QueryWrapper<GradeLevel> queryWrapper = new QueryWrapper<>();
		// queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
		// queryWrapper.eq("grade_id",member.getGradeId());
		// queryWrapper.eq("grade_state",0);
		// if(owner.indexOf("STORE") != -1){
		// owner = "STORE";
		// queryWrapper.like("owner","STORE");
		// }else if(owner.indexOf("BUYER") != -1) {
		// owner = "BUYER";
		// queryWrapper.like("owner","BUYER");
		// }
		// queryWrapper.orderByDesc("end_time");
		// queryWrapper.last("limit 1");
		// GradeLevel gradeLevel = gradeLevelMapper.selectOne(queryWrapper);
		// //充值前先把原有的会员信息禁用
		// gradeLevelMapper.updateByMemberId(UserContext.getCurrentUser().getId(),owner);
		// gradeLevel.setId(UUID.randomUUID().toString().replace("-",
		// "").toLowerCase());
		// gradeLevel.setGradeState(0);
		// gradeLevel.setCreateBy(UserContext.getCurrentUser().getId());
		// gradeLevel.setCreateTime(new Date());
		// gradeLevel.setUpdateBy(null);
		// gradeLevel.setUpdateTime(null);
		// List<GradeVO> gradeVOS = gradeMapper.selectList(new QueryWrapper<>());
		// if(CollectionUtils.isNotEmpty(gradeVOS)){
		// for(GradeVO grade : gradeVOS){
		// if (price.compareTo(grade.getMoney()) == 0 ) {
		// gradeLevel.setGradeId(String.valueOf(grade.getId()));
		// }
		// }
		// }
		// gradeLevel.setOwner(owner);
		// gradeLevelMapper.insert(gradeLevel);
		// }else {
		GradeLevel gradeLevel = new GradeLevel();
		// 获取时间加一年或加一月或加一天
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);// 设置起时间
		cal.add(Calendar.YEAR, 1);// 增加一年
		gradeLevel.setBeginTime(date);
		gradeLevel.setEndTime(cal.getTime());
		gradeLevel.setMemberId(UserContext.getCurrentUser().getId());
		gradeLevel.setGradeState(0);
		List<GradeVO> gradeVOS = gradeMapper.selectList(new QueryWrapper<>());
		if (CollectionUtils.isNotEmpty(gradeVOS)) {
			for (GradeVO grade : gradeVOS) {
				if (price.compareTo(grade.getMoney()) == 0) {
					gradeLevel.setGradeId(String.valueOf(grade.getId()));
				}
			}
		}
		if (owner.indexOf("STORE") != -1) {
			owner = "STORE";
		} else if (owner.indexOf("BUYER") != -1) {
			owner = "BUYER";
		}
		gradeLevel.setOwner(owner);
		gradeLevelMapper.insert(gradeLevel);
		// }
	}

	// 修改商家会员信息
	void updateSeller(Double price, String owner) {

		MemberVO member = memberService.getUserInfos("STORE", null);
		if (member != null && member.getGradeId() != null) {
			QueryWrapper<GradeLevel> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
			queryWrapper.eq("grade_id", member.getGradeId());
			queryWrapper.eq("grade_state", 0);
			if (owner.indexOf("STORE") != -1) {
				owner = "STORE";
				queryWrapper.like("owner", "STORE");
			} else if (owner.indexOf("BUYER") != -1) {
				owner = "BUYER";
				queryWrapper.like("owner", "BUYER");
			}
			queryWrapper.orderByDesc("end_time");
			queryWrapper.last("limit 1");
			GradeLevel gradeLevel = gradeLevelMapper.selectOne(queryWrapper);
			// 充值前先把原有的会员信息禁用
			gradeLevelMapper.updateByMemberId(UserContext.getCurrentUser().getId(), owner);
			gradeLevel.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
			gradeLevel.setGradeState(0);
			gradeLevel.setCreateBy(UserContext.getCurrentUser().getId());
			gradeLevel.setCreateTime(new Date());
			gradeLevel.setUpdateBy(null);
			gradeLevel.setUpdateTime(null);
			GradeVO gradeVOS = gradeMapper.selectOne(new QueryWrapper<GradeVO>().eq("level", "9999"));
			if (gradeVOS != null) {
				gradeLevel.setGradeId(String.valueOf(gradeVOS.getId()));
			}
			StoreDetailVO storeDetail = storeDetailMapper
					.getStoreDetailByMemberId(UserContext.getCurrentUser().getId());
			Store store = new Store();
			store.setId(storeDetail.getStoreId());
			store.setMemberCreateTime(gradeLevel.getBeginTime());
			store.setMemberEndTime(gradeLevel.getEndTime());
			storeMapper.updateById(store);
			gradeLevel.setOwner(owner);
			gradeLevelMapper.insert(gradeLevel);
		} else {
			GradeLevel gradeLevel = new GradeLevel();
			// 获取时间加一年或加一月或加一天
			Date date = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);// 设置起时间
			cal.add(Calendar.YEAR, 1);// 增加一年
			gradeLevel.setBeginTime(date);
			gradeLevel.setEndTime(cal.getTime());
			gradeLevel.setMemberId(UserContext.getCurrentUser().getId());
			gradeLevel.setGradeState(0);
			gradeLevel.setCreateBy(UserContext.getCurrentUser().getId());
			gradeLevel.setCreateTime(new Date());
			GradeVO gradeVOS = gradeMapper.selectOne(new QueryWrapper<GradeVO>().eq("level", "9999"));
			if (gradeVOS != null) {
				gradeLevel.setGradeId(String.valueOf(gradeVOS.getId()));
			}
			StoreDetailVO storeDetail = storeDetailMapper
					.getStoreDetailByMemberId(UserContext.getCurrentUser().getId());
			Store store = new Store();
			store.setId(storeDetail.getStoreId());
			store.setMemberCreateTime(date);
			store.setMemberEndTime(cal.getTime());
			storeMapper.updateById(store);
			if (owner.indexOf("STORE") != -1) {
				owner = "STORE";
			} else if (owner.indexOf("BUYER") != -1) {
				owner = "BUYER";
			}
			gradeLevel.setOwner(owner);
			gradeLevelMapper.insert(gradeLevel);
		}
	}

	/**
	 * 支付订单
	 *
	 * @param payParam
	 *            支付参数
	 * @param cashierParam
	 *            收银台参数
	 */
	public void callBack(PayParam payParam, CashierParam cashierParam) {

		log.info("callBack payParam {}", JSONUtil.toJsonStr(payParam));
		log.info("callBack cashierParam {}", JSONUtil.toJsonStr(payParam));
		Member member = memberService.getById(UserContext.getCurrentUser().getId());

		List<String> ownerList = Arrays.asList(payParam.getOwner().split(","));

		if (StrUtil.equalsAny(payParam.getOrderType(), CashierEnum.TRADE.name(), CashierEnum.ORDER.name())) {// 支付订单
			Order order = orderService.getOrderBySn(cashierParam.getOrderSns());
			order.setOwner(payParam.getOwner());
			orderService.updateById(order);
			Double money = cashierParam.getPrice();// 获取共消费焕呗额
			Store store = storeService.getById(order.getStoreId());
			MemberWallet to = memberWalletService.getMemberWalletInfo(store.getMemberId(), WalletOwnerEnum.SALE.name());
			Double price = order.getGoodsPrice() == null ? 0D : order.getGoodsPrice();// 商品价格
			Double colMoney = order.getFreightPrice() == null ? 0D : order.getFreightPrice();// 运费
			Double comMoney = 0D;
			boolean flag = false;
			if (ownerList.size() > 1) {
				// 组合支付
				flag = memberWalletService.combinedPayOrder(order.getSn(), payParam.getOwner(), member.getId(), to,
						price, colMoney);
			} else {
				String fromOwner = payParam.getOwner();// 钱包类型
				MemberWallet from = memberWalletService.getMemberWalletInfo(member.getId(), fromOwner);
				if (StrUtil.equalsAny(fromOwner, WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
						WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {
					comMoney = CurrencyUtil.mul(price, Double.valueOf(SysDictUtils.getValueString("order_fee")), 5);
					order.setCommission(comMoney);
					// order.setFlowPrice(CurrencyUtil.add(order.getFlowPrice(),comMoney));
					orderService.updateById(order);
				}

				Double totalMoney = CurrencyUtil.add(price, colMoney, comMoney);
				if (NumberUtil.compare(from.getMemberWallet(), totalMoney) < 0) {
					throw new ServiceException(ResultCode.WALLET_INSUFFICIENT);
				}

				flag = memberWalletService.payOrder(order.getSn(), from, to, price, colMoney, comMoney);
				// 推广钱包-会员费-扣款逻辑
				if (fromOwner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
					rechargeFowService.updatePromote(order.getSn(), price, member.getId(), "22");
					if (colMoney != 0D) {
						rechargeFowService.updatePromote(order.getSn(), colMoney, member.getId(), "23");
					}
					rechargeFowService.updatePromote(order.getSn(), comMoney, member.getId(), "24");
				}
				// 支出销售金额
				if (fromOwner.equals(WalletOwnerEnum.SALE.name())) {
					memberWithdrawApplyService.txList(price, order.getSn(), member.getId(), "12");
					if (colMoney != 0D) {
						memberWithdrawApplyService.txList(colMoney, order.getSn(), member.getId(), "13");
					}
					memberWithdrawApplyService.txList(comMoney, order.getSn(), member.getId(), "14");
					// List<MemberSalesWithdrawVO> list = new ArrayList();
					// List<MemberSalesWithdrawVO> sum = memberWithdrawApplyService.getSum();
					// List<MemberSalesWithdrawVO> offlineSum =
					// memberWithdrawApplyService.getOfflineSum();
					// List<MemberSalesWithdrawVO> memberSalesWithdrawVOS =
					// memberWithdrawApplyService.merchandiseStatus();
					// BigDecimal flowprice = BigDecimal.valueOf(0);//焕呗总额
					// BigDecimal surplus = BigDecimal.valueOf(0);//剩余可提现额度
					// for (MemberSalesWithdrawVO item : sum) {
					// flowprice =
					// flowprice.add(BigDecimal.valueOf(item.getFlowprice().toString()));
					// surplus = surplus.add(BigDecimal.valueOf(item.getSurplus().toString()));
					// item.setFlowpriceSum(flowprice);
					// item.setSurplusSum(surplus);
					// BigDecimal divide = surplus.divide(flowprice, 5);
					// item.setFeeSum(divide.doubleValue());
					// list.add(item);
					// }
					// for (MemberSalesWithdrawVO item : offlineSum) {
					// flowprice =
					// flowprice.add(BigDecimal.valueOf(item.getFlowprice().toString()));
					// surplus = surplus.add(BigDecimal.valueOf(item.getSurplus().toString()));
					// item.setFlowpriceSum(flowprice);
					// item.setSurplusSum(surplus);
					// BigDecimal divide = surplus.divide(flowprice, 5);
					// item.setFeeSum(divide.doubleValue());
					// list.add(item);
					// }
					// for (MemberSalesWithdrawVO item : memberSalesWithdrawVOS) {
					// flowprice =
					// flowprice.add(BigDecimal.valueOf(item.getFlowprice().toString()));
					// surplus = surplus.add(BigDecimal.valueOf(item.getSurplus().toString()));
					// item.setFlowpriceSum(flowprice);
					// item.setSurplusSum(surplus);
					// BigDecimal divide = surplus.divide(flowprice, 5);
					// item.setFeeSum(divide.doubleValue());
					// list.add(item);
					// }
					// List<MemberSalesWithdrawVO> search = search(list);
					// Double sub = 0.00;
					// Double flow = 0.00;
					// Double subtract = 0.00;
					// Double dici=0.00;//接受第一次要累加的焕呗额
					// Double dier=0.00;
					// Double sumMoney = totalMoney;
					// BigDecimal hbmoney =
					// BigDecimal.valueOf(totalMoney.toString());//吧double类型转为BigDecimal
					// BigDecimal jineMax = BigDecimal.valueOf(0); //本次账单累计提现金额
					// String sn = SnowFlake.createStr("W");
					// for (MemberSalesWithdrawVO item : search) {
					// BigDecimal surp =
					// BigDecimal.valueOf(item.getFlowprice().toString());//焕呗这条记录一共多少
					// BigDecimal sy = BigDecimal.valueOf(item.getSurplus().toString());//人民币还剩提现
					// Double surpx = item.getSurplus();
					// flow = CurrencyUtil.add(flow, item.getFlowprice());//焕呗总额
					// Double mul = CurrencyUtil.mul(item.getFlowprice(), item.getFee(),
					// 5);//本笔订单提现金额
					// sub = CurrencyUtil.add(sub, mul);//总提现金额
					// if (hbmoney.compareTo(sy) == 1) {
					// Double jine = CurrencyUtil.mul(flow.doubleValue(), item.getFee());//用户实际提现的金额
					// jineMax = jineMax.add(BigDecimal.valueOf(jine.toString()));
					// dici=jineMax.doubleValue();
					// subtract = CurrencyUtil.sub(flow,jine);
					// hbmoney = hbmoney.subtract(BigDecimal.valueOf(flow.toString()));//
					// memberWithdrawApplyService.batchUpdate("-1", 0.0, item.getId(),
					// "0.0");//修改已经提现完的订单
					// item.setFlowprice(sumMoney.doubleValue());//用于前端回显
					// item.setCreateTime(new Date());
					// item.setPayPrice(sy);
					// item.setTxsn(sn);
					// MemberWithdrawItem dto = new MemberWithdrawItem();
					// dto.setApplyMoney(flow.doubleValue());
					// dto.setRealMoney(jine);
					// dto.setOrderItemId(order.getId());
					// dto.setFee(item.getFee());
					// dto.setSn(order.getSn());
					// dto.setCreateTime(new Date());
					// memberWalletItemService.AddItem(dto);
					// if (hbmoney.compareTo(BigDecimal.valueOf(0)) == 0) {
					// break;
					// }
					// } else {
					// BigDecimal fix = BigDecimal.valueOf(0);
					// fix = surp.subtract(hbmoney);
					// Double jine = CurrencyUtil.mul(hbmoney.doubleValue(),
					// item.getFee());//用户实际提现的金额
					// dier= CurrencyUtil.add(jine,dici);
					// subtract = hbmoney.subtract(BigDecimal.valueOf(jine)).doubleValue();//提现手续费
					// Double mul1 = CurrencyUtil.mul(fix.doubleValue(), item.getFee());//
					// item.setFlowprice(fix.doubleValue());//本次扣款焕呗额
					// item.setCreateTime(new Date());
					// item.setPayPrice(jine.toString());
					// item.setTxsn(sn);
					// memberWithdrawApplyService.batchUpdate("0", fix.doubleValue(), item.getId(),
					// mul1.toString());
					// MemberWithdrawItem dto = new MemberWithdrawItem();
					// dto.setApplyMoney(hbmoney.doubleValue());
					// dto.setMemberId(member.getId());
					// dto.setRealMoney(jine);
					// dto.setOrderItemId(order.getId());
					// dto.setSn(order.getSn());
					// dto.setFee(item.getFee());
					// dto.setCreateTime(new Date());
					// memberWalletItemService.AddItem(dto);
					// break;
					// }
					// }
				}

			}
			if (StringUtils.isNotEmpty(order.getConsigneeAddressIdPath())
					&& StringUtils.isEmpty(member.getLocation())) {
				String addressId = order.getConsigneeAddressIdPath()
						.substring(order.getConsigneeAddressIdPath().lastIndexOf(",") + 1);
				Region region = regionMapper.selectById(addressId);
				member.setLocation(region.getAdCode());
				memberMapper.updateById(member);
			}
			if (flag) {
				order = orderService.getOrderBySn(cashierParam.getOrderSns());
				order.setFlowPrice(CurrencyUtil.add(order.getFlowPrice(),
						order.getCommission() != null ? order.getCommission() : 0D));
				// 下面是自提的信息，需要生成核销码，将核销码放到数据库中
				if ("SELF_PICK_UP".equals(order.getDeliveryMethod())) {
					order.setVerificationCode(orderService.getCode(order.getStoreId()));
					order.setDeliverStatus(DeliverStatusEnum.DELIVERED.name());
				}
				orderService.updateById(order);
				PaymentSuccessParams paymentSuccessParams = new PaymentSuccessParams(PaymentMethodEnum.WALLET.name(),
						"", price, payParam);
				paymentService.success(paymentSuccessParams);
			}

		} else {
			if (ownerList.size() == 1) {
				String fromOwner = payParam.getOwner();// 钱包类型
				MemberWallet from = memberWalletService.getMemberWalletInfo(member.getId(), fromOwner);

				if (StrUtil.equals(payParam.getOrderType(), CashierEnum.MEMBER.name())) {// 缴纳会员费
					Double price = cashierParam.getPrice();// 交易金额
					memberWalletService.upgradHy(cashierParam.getOrderSns(), from, price);
					updateMember(price, payParam.getOwner());
					Recharge recharge = rechargeService.getRecharge(cashierParam.getOrderSns());
					saveRechargeFow(recharge);
				}
			}
		}
	}

	/**
	 * 获取区域代理商
	 *
	 * @param memberId
	 * @return
	 */
	public String getProxy(String memberId) {
		Member member = memberService.getById(memberId);
		if (ObjectUtil.isNotNull(member) && StrUtil.isNotEmpty(member.getLocation())) {
			String code = member.getLocation();
			String province = StrUtil.concat(true, StrUtil.subPre(code, 2), "0000");
			String city = StrUtil.concat(true, StrUtil.subPre(code, 4), "00");

			QueryWrapper<Partner> wrapper = new QueryWrapper<>();
			wrapper.eq("partner_type", "4");// 代理商
			wrapper.eq("delete_flag", 0);
			wrapper.eq("audit_state", "PASS");
			wrapper.in("region_id", province, city, code);
			wrapper.orderByDesc("region_id");
			wrapper.last("limit 1");
			Partner one = partnerService.getOne(wrapper);
			if (null != one) {
				return one.getMemberId();
			}
		}
		return null;
	}

	/**
	 * 充值会员成功，插入充值明细表
	 */
	public void saveRechargeFow(Recharge recharge) {
		RechargeFow rechargeFow = new RechargeFow();
		rechargeFow.setSn(recharge.getRechargeSn());
		Double ts = Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.MEMBERSHIP_RATE.dictCode(), "天使合伙人"));

		String proxyUser = getProxy(recharge.getMemberId());
		if (StringUtils.isNotEmpty(proxyUser)) {
			rechargeFow.setMemberId(proxyUser);// 城市合伙人
			Double cs = Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(), "城市合伙人"));
			Double csFee = cs;
			// 查询上级推广人身份
			Member member = getExtMember(recharge.getMemberId());
			if (null != member) {
				QueryWrapper<Partner> query = new QueryWrapper<>();
				query.eq("member_id", member.getId());
				query.eq("partner_state", "0");
				query.eq("delete_flag", "0");
				query.last("limit 1");
				Partner partner = partnerService.getOne(query);
				// 推广人是天使
				if (partner != null && 2 == partner.getPartnerType()) {
					csFee = CurrencyUtil.mul(CurrencyUtil.sub(1D, ts), cs);
				} else {
					csFee = cs;
				}
			}
			rechargeFow.setHuanBei(CurrencyUtil.mul(recharge.getRechargeMoney(), csFee));
			rechargeFow.setCanHuanBei(CurrencyUtil.mul(recharge.getRechargeMoney(), csFee));
			rechargeFow.setAddTime(recharge.getCreateTime());
			rechargeFow.setRechargeType(recharge.getRechargeType());
			Double fee = 0D;
			// List<SysDictItemVO> allValue =
			// SysDictUtils.getAllValue(DictCodeEnum.MEMBERSHIP_PRICE.dictCode());
			// if (null != allValue) {
			// for (SysDictItemVO sysDictItemVO : allValue) {
			// Double val = Double.parseDouble(sysDictItemVO.getItemValue());
			// if (val.compareTo(recharge.getRechargeMoney()) == 0) {
			// fee =
			// Double.parseDouble(SysDictUtils.getValueString(DictCodeEnum.RECHARGE_RULE.dictCode(),
			// sysDictItemVO.getItemText()));
			// break;
			// }
			// }
			// }
			QueryWrapper<GradeVO> queryWrapper = Wrappers.query();
			queryWrapper.eq("mc.delete_flag", 0);
			queryWrapper.orderByDesc("mc.create_time");
			List<GradeVO> byMemberVO = gradeMapper.findByMemberVO(queryWrapper);
			if (null != byMemberVO) {
				for (GradeVO vo : byMemberVO) {
					Double val = vo.getMoney();
					if (val.compareTo(recharge.getRechargeMoney()) == 0) {
						fee = vo.getRechargeRule();
						break;
					}
				}
			}

			rechargeFow.setFee(fee);
			rechargeFow.setMoney(CurrencyUtil.mul(CurrencyUtil.mul(recharge.getRechargeMoney(), csFee), fee));
			rechargeFow.setCanMoney(CurrencyUtil.mul(CurrencyUtil.mul(recharge.getRechargeMoney(), csFee), fee));
			rechargeFow.setRealization("0");
			rechargeFowService.save(rechargeFow);
		}
	}

	/**
	 * 获取当前用户的推广人
	 * 
	 * @param memberId
	 * @return
	 */
	public Member getExtMember(String memberId) {
		QueryWrapper<Extension> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.last("limit 1");
		Extension extension = eextensionService.getOne(queryWrapper);
		if (cn.hutool.core.util.ObjectUtil.isNotNull(extension)) {
			QueryWrapper<Member> queryWrapper1 = new QueryWrapper();
			queryWrapper1.eq("promotion_code", extension.getExtension());
			queryWrapper1.eq("delete_flag", "0");
			queryWrapper1.last("limit 1");
			Member member = memberService.getOne(queryWrapper1);
			if (ObjectUtil.isNotNull(member)) {
				log.info("用户{}绑定的推广码{},推广人为{}", memberId, extension.getExtension(), member.getId());
				return member;
			}

		}
		return null;
	}

	// 扫码支付回调
	public void callBackNative(PayParam payParam, CashierParam cashierParam) {

		log.info("callBackNative payParam {}", JSONUtil.toJsonStr(payParam));
		log.info("callBackNative cashierParam {}", JSONUtil.toJsonStr(payParam));

		List<String> ownerList = Arrays.asList(payParam.getOwner().split(","));

		Member member = memberService.getById(UserContext.getCurrentUser().getId());
		Order order = orderService.getOrderBySn(cashierParam.getOrderSns());
		order.setOwner(payParam.getOwner());
		Store store = storeService.getById(order.getStoreId());
		order.setStoreName(store.getStoreName());
		String memberId = store.getMemberId();// 获取 店铺的 用户

		MemberWallet to = memberWalletService.getMemberWalletInfo(memberId, WalletOwnerEnum.SALE.name());
		Double money = cashierParam.getPrice();// 交易金额
		Double comMoney = 0D;
		boolean flag = false;

		if (ownerList.size() > 1) {
			// 组合支付
			flag = memberWalletService.combinedPay(order.getSn(), payParam.getOwner(), member.getId(), to, money);
		} else {
			String fromOwner = payParam.getOwner();// 钱包类型
			MemberWallet from = memberWalletService.getMemberWalletInfo(member.getId(), fromOwner);

			if (StrUtil.equalsAny(fromOwner, WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
					WalletOwnerEnum.PROMOTE_HY.name(), WalletOwnerEnum.PROMOTE_FW.name())) {
				comMoney = CurrencyUtil.mul(money,
						Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 5);
				order.setCommission(comMoney);
			}

			Double totalMoney = money + comMoney;
			order.setFlowPrice(totalMoney);
			orderService.updateById(order);
			if (NumberUtil.compare(from.getMemberWallet(), totalMoney) < 0) {
				throw new ServiceException(ResultCode.WALLET_INSUFFICIENT);
			}

			flag = memberWalletService.scanPay(cashierParam.getOrderSns(), from, to, money, comMoney);

			if (fromOwner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
				rechargeFowService.updatePromote(order.getSn(), money, member.getId(), "22");
				rechargeFowService.updatePromote(order.getSn(), comMoney, member.getId(), "24");
			}
			// 支出销售金额
			if (fromOwner.equals(WalletOwnerEnum.SALE.name())) {
				memberWithdrawApplyService.txList(money, order.getSn(), member.getId(), "12");
				memberWithdrawApplyService.txList(comMoney, order.getSn(), member.getId(), "14");
			}
		}

		if (StringUtils.isNotEmpty(store.getStoreAddressIdPath()) && StringUtils.isEmpty(member.getLocation())) {
			String addressId = store.getStoreAddressIdPath()
					.substring(store.getStoreAddressIdPath().lastIndexOf(",") + 1);
			Region region = regionMapper.selectById(addressId);
			member.setLocation(region.getAdCode());
			memberMapper.updateById(member);
		}

		if (flag) {
			orderService.updateById(order);
			if (order.getOrderType() == "OFFLINE" || order.getOrderType().equals("OFFLINE")) {
				List<OrderItem> orderItems = new ArrayList<>();
				OrderItem orderItem = new OrderItem();
				orderItem.setOrderSn(order.getSn());// 线下sn
				orderItem.setTradeSn(order.getSn());
				orderItem.setGoodsPrice(order.getGoodsPrice());
				orderItem.setFlowPrice(order.getFlowPrice());// 焕呗总额
				// 有合同 并且 有折扣率
				if ("1".equals(store.getIsHaveContract()) && StringUtils.isNotEmpty(store.getDiscount())
						&& store.getDiscount() != "null") {
					// orderItem.setFee(Double.valueOf(SysDictUtils.getValueString("promote_withdrawal_rate",
					// "商家")));
					// 折现率
					orderItem.setFee(CurrencyUtil.div(Double.valueOf(store.getDiscount()), 100D));// 折现率
					orderItem.setDeposit(CurrencyUtil.mul(orderItem.getFlowPrice(), orderItem.getFee()));// 计算可提现金额
					orderItem.setSurplus(orderItem.getDeposit());// 剩余可提现金额
				} else {
					orderItem.setFee(0D);// 折现率
					orderItem.setDeposit(0D);// 计算可提现金额
					orderItem.setSurplus(0D);// 剩余可提现金额
				}
				orderItem.setRealization(0);
				orderItem.setSurplusPrice(order.getFlowPrice());
				orderItems.add(orderItem);
				orderItemService.saveBatch(orderItems);
			}
			PaymentSuccessParams paymentSuccessParams = new PaymentSuccessParams(PaymentMethodEnum.WALLET.name(), "",
					money, payParam);
			paymentService.success(paymentSuccessParams);

			// updatePartner(payParam.getOrderType(),money);
			// 绑定推广码
			// eextensionService.bindEx(member.getId(),target.getPromotionCode());
		}
	}

	// 转账支付回调
	public void callBackTransfer(PayParam payParam, CashierParam cashierParam) {

		log.info("callBackNative payParam {}", JSONUtil.toJsonStr(payParam));
		log.info("callBackNative cashierParam {}", JSONUtil.toJsonStr(payParam));

		List<String> ownerList = Arrays.asList(payParam.getOwner().split(","));

		Transfer transfer = transferService.getTransferBySn(cashierParam.getOrderSns());
		Member payer = memberService.getById(transfer.getPayer());// 付款人
		Member payee = memberService.getById(transfer.getPayee());// 收款人

		MemberWallet to = memberWalletService.getMemberWalletInfo(payee.getId(), WalletOwnerEnum.RECHARGE.name());
		Double money = cashierParam.getPrice();// 交易金额
		Double comMoney = 0D;
		boolean flag = false;

		if (ownerList.size() > 1) {
			// 组合支付
			flag = memberWalletService.combinedTransferPay(transfer.getSn(), payParam.getOwner(), payer.getId(), to,
					money);
		} else {
			String fromOwner = payParam.getOwner();// 钱包类型
			MemberWallet from = memberWalletService.getMemberWalletInfo(payer.getId(), fromOwner);

			if (StrUtil.equalsAny(fromOwner, WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE_FW.name(),
					WalletOwnerEnum.PROMOTE.name(), WalletOwnerEnum.PROMOTE_HY.name())) {
				comMoney = CurrencyUtil.mul(money,
						Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 5);
				transfer.setCommission(comMoney);
			}

			Double totalMoney = money + comMoney;
			if (NumberUtil.compare(from.getMemberWallet(), totalMoney) < 0) {
				throw new ServiceException(ResultCode.WALLET_INSUFFICIENT);
			}
			// TRANSFER 转账
			flag = memberWalletService.transferPay(cashierParam.getOrderSns(), from, to, money, comMoney, "TRANSFER");
			// 推广钱包-会员费-扣款逻辑
			if (fromOwner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
				rechargeFowService.updatePromote(cashierParam.getOrderSns(), money, payer.getId(), "26");
				rechargeFowService.updatePromote(cashierParam.getOrderSns(), comMoney, payer.getId(), "27");
			}
			// 支出销售金额
			if (fromOwner.equals(WalletOwnerEnum.SALE.name())) {
				memberWithdrawApplyService.txList(money, cashierParam.getOrderSns(), payer.getId(), "16");
				memberWithdrawApplyService.txList(comMoney, cashierParam.getOrderSns(), payer.getId(), "17");
			}
		}
		if (flag) {
			PaymentSuccessParams paymentSuccessParams = new PaymentSuccessParams(PaymentMethodEnum.WALLET.name(), "",
					money, payParam);
			paymentService.success(paymentSuccessParams);
			transfer.setPaymentTime(new Date());
			transfer.setState("success");
			transferService.updateById(transfer);
			// updatePartner(payParam.getOrderType(),money);
			// 绑定推广码
			// eextensionService.bindEx(member.getId(),target.getPromotionCode());
		} else {
			transfer.setState("fail");
			transferService.updateById(transfer);
		}
	}

	public List<MemberSalesWithdrawVO> search(List<MemberSalesWithdrawVO> logsList) {
		Collections.sort(logsList, new Comparator<MemberSalesWithdrawVO>() {
			@Override
			public int compare(MemberSalesWithdrawVO o1, MemberSalesWithdrawVO o2) {
				if ((o1.getFee() > o2.getFee())) {
					return 1;
				}
				if (o1.getFee() == o2.getFee()) {
					return 0;
				}
				return -1;
			}
		});
		return logsList;
	}

	public List<MemberSalesWithdrawVO> searchs(List<MemberSalesWithdrawVO> logsList) {
		Collections.sort(logsList, new Comparator<MemberSalesWithdrawVO>() {
			@Override
			public int compare(MemberSalesWithdrawVO o1, MemberSalesWithdrawVO o2) {
				if ((o1.getFee() > o2.getFee())) {
					return -1;
				}
				if (o1.getFee() == o2.getFee()) {
					return 0;
				}
				return 1;
			}
		});
		return logsList;
	}
}
